package com.adu.music.spider;

import com.adu.music.parser.PlaylistParser;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author duchuanchuan
 * @date 2017/1/4
 */
public class PlaylistUpdateSpider extends AbstractSpider {
    private int pageIndex = 0;
    private final int pageSize = 100;

    @Override
    protected void initTaskQueue() {
        List<Map<String, Object>> playlists = queryPlaylistByIndex(pageIndex);
        playlists.forEach(pl -> putTaskToQueue(pl.get("id")));
        pageIndex++;
    }

    private List<Map<String, Object>> queryPlaylistByIndex(int index) {
        final String sql = "select id from playlist where play>999999 or share > 999 or comment>999 or favorite>9999 limit :offset,:size";
        Map<String, Object> paramMap = new HashMap<>(2);
        paramMap.put("offset", index * pageSize);
        paramMap.put("size", pageSize);
        return asyncNamedParameterJdbcTemplate.queryForList(sql, paramMap);
    }

    @Override
    protected void produceTask() {
        while (!Thread.interrupted()) {
            List<Map<String, Object>> playlists = queryPlaylistByIndex(pageIndex);
            playlists.forEach(pl -> putTaskToQueue(pl.get("id")));
            if (playlists.size() < pageSize) break;
            pageIndex++;
        }
    }

    @Override
    protected void consumeTask(Object task) {
        String playlistId = String.valueOf(task);
        Map<String, Object> map = PlaylistParser.parsePlaylistById(playlistId);
        String sql = "update playlist set comment=:comment,play=:play,share=:share,favorite=:favorite,updated_at=now() where id=:id";
        if (!map.isEmpty()) asyncNamedParameterJdbcTemplate.update(sql, map);
    }
}
